<template>
    <div class="comment-scroll-container" id="comment-content">
        <ul class="comment-list" ref="commentList">
            <li v-for="(item, index) in comments" :key="index" class="comment-item">
                {{ item.user_grade_level }} {{ item.userNick }} : {{ item.chat_msg }}
            </li>
        </ul>
    </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';

const props = defineProps({
    comments: {
        type: Array,
        required: true,
        default: () => []
    }
});

const commentList = ref(null);

watch(
    () => props.comments,
    () => {
        nextTick(() => {
            scrollToBottom()
        });
    },
    { deep: true }
);

// 有新消息对话框自动滚动到最新消息处
const scrollToBottom = () => {
    const el = document.getElementById("comment-content")
    if (el) {
        setTimeout(() => {
            el.scrollTop = el.scrollHeight;
        }, 0)
    }
}
</script>

<style scoped>
.comment-scroll-container {
    height: 200px;
    overflow-y: auto;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
}

.comment-list {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

.comment-item {
    padding: 5px 0;
    border-bottom: 1px solid #eee;
    text-align: left;
}

.comment-item:last-child {
    border-bottom: none;
}
</style>